package com.jy.api.okhttp;


import com.alibaba.nacos.common.utils.MapUtils;
import org.springframework.http.*;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @ename wade.nie
 * @cname 聂敏
 * @email 550552699@qq.com
 * @date 2024/7/15
 */
public abstract class AbstractThirdClient implements IThirdClient {

    private RestTemplate restTemplate;

    public AbstractThirdClient(RestTemplate restTemplate){
        this.restTemplate = restTemplate;
    }

    @Override
    public ResponseEntity<String> execute(String url, Map<String, String> headers, HttpMethod method, MediaType mediaType, String paramsBody, Map<String, ?> uriVariables) {
        Assert.hasText(url, "请求Url必传");
        Assert.notNull(method, "请求method必传");
        Assert.notNull(mediaType, "请求mediaType必传");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(mediaType);
        if (MapUtils.isNotEmpty(headers)) {
            httpHeaders.setAll(headers);
        }

        HttpEntity<String> requestEntity = new HttpEntity<String>(paramsBody, httpHeaders);
        return restTemplate.exchange(url, method, requestEntity, String.class, uriVariables);
    }

    /**
     * http 是否正常响应
     */
    protected boolean isSuccess(ResponseEntity<String> responseEntity) {
        return responseEntity.getStatusCode() == HttpStatus.OK;
    }
}
